//
//  WDPersonMessageView.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/11/30.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDPersonMessageView.h"
#import "WDPersonMessage.h"
#import "BDImagePicker.h"

typedef void (^pickerFinish)();

@interface WDPersonMessageView ()
/** 头像 */
@property(nonatomic, weak) UIImageView *iconImage;
/** 姓名 */
@property(nonatomic, weak) UILabel *nameLabel;
/** 职位 */
@property(nonatomic, weak) UILabel *leftJobLabel;
/** 电话 */
@property(nonatomic, weak) UILabel *leftPhoneLabel;
/** 邮箱 */
@property(nonatomic, weak) UILabel *leftMailLabel;
/** 具体职位 */
@property (nonatomic, weak) UILabel *jobLabel;
/** 电话号码 */
@property (nonatomic, weak) UILabel *phoneLabel;
/** 邮箱地址 */
@property (nonatomic, weak) UILabel *mailLabel;

@end

@implementation WDPersonMessageView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor whiteColor];
        
        UIImageView *imageView = [[UIImageView alloc] init];
        
        [imageView sd_setImageWithURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"userIcon"]] placeholderImage:[UIImage imageNamed:@"defaultIcon"]];
        
        //设置图片可点击
        imageView.userInteractionEnabled = YES;
        
        //添加手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapIcon)];
        [tap setNumberOfTapsRequired:1];
        [tap setNumberOfTapsRequired:1];
        [imageView addGestureRecognizer:tap];
        
        [self addSubview:imageView];
        self.iconImage = imageView;
        
        self.nameLabel = [self setUpLabelWithText:[[NSUserDefaults standardUserDefaults] objectForKey:@"personName"] textAlignment:NSTextAlignmentRight];
        
        self.jobLabel = [self setUpLabelWithText:[[NSUserDefaults standardUserDefaults] objectForKey:@"positionDesc"] textAlignment:NSTextAlignmentRight];
        
        self.phoneLabel = [self setUpLabelWithText:[[NSUserDefaults standardUserDefaults] objectForKey:@"personPhone"] textAlignment:NSTextAlignmentRight];
        
        self.mailLabel = [self setUpLabelWithText:[[NSUserDefaults standardUserDefaults] objectForKey:@"userName"] textAlignment:NSTextAlignmentRight];
        
        self.leftJobLabel = [self setUpLabelWithText:@"职位" textAlignment:NSTextAlignmentLeft];
        
        self.leftPhoneLabel = [self setUpLabelWithText:@"电话" textAlignment:NSTextAlignmentLeft];
        
        self.leftMailLabel = [self setUpLabelWithText:@"邮箱" textAlignment:NSTextAlignmentLeft];
        
        //布局子控件
        [self.iconImage makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.centerX);
            make.width.height.equalTo(60);
            make.top.equalTo(32.5);
        }];
        self.iconImage.layer.cornerRadius = 30;
        self.iconImage.clipsToBounds = YES;
        
        [self.nameLabel makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.centerX);
            make.top.equalTo(self.iconImage.bottom).offset(10);
        }];
        
        [self.leftJobLabel makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.nameLabel.bottom).offset(30);
            make.left.equalTo(15);
        }];
        
        [self.leftPhoneLabel makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.leftJobLabel.left);
            make.top.equalTo(self.leftJobLabel.bottom).offset(22.5);
        }];
        
        [self.leftMailLabel makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.leftPhoneLabel.left);
            make.top.equalTo(self.leftPhoneLabel.bottom).offset(22);
        }];
        
        [self.jobLabel makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.equalTo(self.leftJobLabel.top);
            make.right.equalTo(-15);
        }];
        
        [self.phoneLabel makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.equalTo(self.leftPhoneLabel.top);
            make.right.equalTo(self.jobLabel.right);
        }];
        
        [self.mailLabel makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.equalTo(self.leftMailLabel.top);
            make.right.equalTo(self.jobLabel.right);
        }];
    }
    return self;
}

- (UILabel *)setUpLabelWithText:(NSString *)text textAlignment:(NSTextAlignment)textAlignment
{
    UILabel *label = [[UILabel alloc] init];
    
    label.text = text;
    
    label.textAlignment = textAlignment;
    
    label.textColor = ColorForRGB(0x6b6b6b);
    
    label.font = [UIFont systemFontOfSize:15];
    
    [self addSubview:label];
    
    return label;
}

//点击手势
- (void)tapIcon
{
    [BDImagePicker showImagePickerFromViewController:_delegete allowsEditing:YES finishAction:^(UIImage *image) {
        if (image) {
           
            NSData *imageData = UIImagePNGRepresentation(image);
            
            [SVProgressHUD show];
            
            [self upLoadImageWithData:imageData complete:^{
                
                [SVProgressHUD dismiss];
                
            }];
        }
    }];
    
}

#pragma mark - 头像上传
- (void)upLoadImageWithData:(NSData *)imageData complete:(pickerFinish)complete
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSDictionary *parameters = @{
                                 @"uid" : [[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],
                                 @"ctype":@3
                                 };
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLUploadImage];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //上传头像
        
        // 可以在上传时使用当前的系统时间作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
        
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //WDLog(@"%@", responseObject);
        
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        
        [userDefault setObject:responseObject[@"image_url"] forKey:@"userIcon"];
        
        [self.iconImage sd_setImageWithURL:[NSURL URLWithString:responseObject[@"image_url"]]];
        
        complete();
        
        //WDLog(@"上传成功");
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //WDLog(@"上传失败");
        
        complete();
    }];
}

- (void)setPersonMessage:(WDPersonMessage *)personMessage
{
    _personMessage = personMessage;
    
    [self.iconImage sd_setImageWithURL:[NSURL URLWithString:personMessage.iconImage] placeholderImage:[UIImage imageNamed:@"defaultIcon"]];
    self.nameLabel.text = personMessage.name;
    self.jobLabel.text = personMessage.position;
    self.phoneLabel.text = personMessage.phoneNumber;
    self.mailLabel.text = personMessage.mailAddress;
    
    [self layoutIfNeeded];
    
    personMessage.viewH = CGRectGetMaxY(self.mailLabel.frame) + 20;
    
}

@end
